import G6 from '@antv/g6';
import React from 'react';
import ResizePolyfill from 'resize-observer-polyfill';
import {debounce} from 'lodash';

let uniqueId = 0;

function generateUniqueId() {
  return `rc-g6-${uniqueId++}`;
}

interface IProps {
  data?: any;
  width: number;
  height: number;
  chartConfig?: {};
  configs?: any;
  g6Config?: any;
}

export default function createG6(__operation: any) {
  class Component extends React.Component<IProps> {
    private graph: any;
    private graphId: any;
    private onRef: any;

    constructor(props: any, context: any) {
      super(props, context);
      this.graph = null;
      this.onRef = null;
      this.graphId = generateUniqueId();
    }

    componentDidMount() {
      this.initGraph(this.props);
    }

    componentWillReceiveProps(newProps: any) {
      const {data: newData, width: newWidth, height: newHeight} = newProps;
      const {data: oldData, width: oldWidth, height: oldHeight} = this.props;

      if (newData !== oldData) {
        this.graph.changeData(newData);
      }
      if (newWidth !== oldWidth || newHeight !== oldHeight) {
        this.graph.changeSize(newWidth, newHeight);
      }
    }

    shouldComponentUpdate() {
      return false;
    }

    componentWillUnmount() {
      this.graph.destroy();
      this.graph = null;
      this.graphId = null;
    }



    initGraph(props: IProps) {
      const {width, height,g6Config, configs} = props;

      const graph = new G6.TreeGraph({
        container: this.graphId,
        width,
        height,
        ...g6Config
      });
      __operation(graph, configs,this.graphId);
      this.graph = graph;
    }

    render() {
      return (
        <div
          id={this.graphId}
          ref={(ref) => (this.onRef = ref)}
          style={{width: '100%', height: '100%'}}
        />
      );
    }
  }

  return Component;
}
